import { api, getCurrentUser } from './api.js';

document.addEventListener('DOMContentLoaded', async () => {
    // 检查登录状态
    const user = await getCurrentUser();
    if (!user) {
        window.location.href = 'index.html';
        return;
    }

    // 加载分类和菜品
    await loadCategories();
    await loadDishes();

    // 绑定分类筛选事件
    document.getElementById('category-select').addEventListener('change', (e) => {
        loadDishes(e.target.value);
    });

    // 绑定退出事件
    document.getElementById('logout-btn').addEventListener('click', handleLogout);
});

// 加载分类
async function loadCategories() {
    try {
        const categories = await api.get('/menu/categories');
        const categoriesList = document.getElementById('categories-list');
        const categorySelect = document.getElementById('category-select');

        // 清空现有内容
        categoriesList.innerHTML = '';
        categorySelect.innerHTML = '<option value="0">所有分类</option>';

        // 添加分类到筛选器和列表
        categories.forEach(category => {
            // 添加到下拉筛选
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.name;
            categorySelect.appendChild(option);

            // 添加到分类列表
            const categoryCard = document.createElement('div');
            categoryCard.className = 'category-card';
            categoryCard.dataset.id = category.id;
            categoryCard.innerHTML = `
                <h3>${category.name}</h3>
                <p>${category.description || ''}</p>
            `;
            
            // 点击分类筛选菜品
            categoryCard.addEventListener('click', () => {
                document.querySelectorAll('.category-card').forEach(card => {
                    card.classList.remove('active');
                });
                categoryCard.classList.add('active');
                loadDishes(category.id);
            });
            
            categoriesList.appendChild(categoryCard);
        });

        // 默认选中第一个分类
        if (categories.length > 0) {
            categoriesList.firstChild.classList.add('active');
        }
    } catch (error) {
        console.error('加载分类失败:', error);
        alert('加载分类失败，请刷新页面重试');
    }
}

// 加载菜品
async function loadDishes(categoryId = 0) {
    try {
        let endpoint = '/menu/dishes';
        if (categoryId > 0) {
            endpoint += `?category_id=${categoryId}`;
        }

        const dishes = await api.get(endpoint);
        const dishesGrid = document.getElementById('dishes-grid');
        
        // 清空现有内容
        dishesGrid.innerHTML = '';

        if (dishes.length === 0) {
            dishesGrid.innerHTML = '<p class="no-dishes">该分类下暂无菜品</p>';
            return;
        }

        // 添加菜品到网格
        dishes.forEach(dish => {
            const dishCard = document.createElement('div');
            dishCard.className = 'dish-card';
            dishCard.innerHTML = `
                <img src="assets/images/dishes/${dish.id}.jpg" alt="${dish.name}" class="dish-image" onerror="this.src='assets/images/dishes/default.jpg'">
                <div class="dish-info">
                    <h3 class="dish-title">${dish.name}</h3>
                    <p class="dish-description">${dish.description || '暂无描述'}</p>
                    <div class="dish-footer">
                        <span class="dish-price">¥${dish.price.toFixed(2)}</span>
                        <span class="dish-stock">库存: ${dish.stock}</span>
                    </div>
                    <button class="add-to-cart" data-dish-id="${dish.id}" ${dish.stock <= 0 ? 'disabled' : ''}>
                        ${dish.stock <= 0 ? '已售罄' : '加入购物车'}
                    </button>
                </div>
            `;
            
            dishesGrid.appendChild(dishCard);
        });

        // 绑定加入购物车事件
        document.querySelectorAll('.add-to-cart').forEach(button => {
            button.addEventListener('click', (e) => {
                const dishId = e.target.dataset.dishId;
                addToCart(dishId);
            });
        });
    } catch (error) {
        console.error('加载菜品失败:', error);
        alert('加载菜品失败，请刷新页面重试');
    }
}

// 加入购物车
async function addToCart(dishId) {
    try {
        // 这里可以添加购物车逻辑，或者直接跳转到下单页面
        sessionStorage.setItem('selectedDish', dishId);
        window.location.href = 'order.html';
    } catch (error) {
        console.error('添加到购物车失败:', error);
        alert('添加到购物车失败，请重试');
    }
}

// 处理退出登录
async function handleLogout() {
    try {
        await api.post('/auth/logout');
        window.location.href = 'index.html';
    } catch (error) {
        console.error('退出登录失败:', error);
        alert('退出登录失败，请重试');
    }
}